#include <vector>
#include "RightManager.h"
#include "Configuration.h"
#include "ChannelRight.h"

IRightManager*	RightManager::_instance = NULL;

RightManager::RightManager()
{
}

IRightManager*	RightManager::GetRightManager()
{
	if (RightManager::_instance == NULL)
		RightManager::_instance = new RightManager();
	return RightManager::_instance;
}

const IChannelRight&		RightManager::GetChannelRight(IUser* user, IChannel* channel)
{
	if(this->_userChannelRight.count(user) && this->_userChannelRight[user].count(channel))
		return *(this->_userChannelRight[user][channel]);
	IDatabase::DbResult* result = Configuration::GetConfiguration()->GetDatabase()->SelectChannelRight(user->GetId(), channel->GetId());
	if (result->size() == 0)
	{
		//creer un nouveau channelright base sur celui par default
		delete result;
		Configuration::GetConfiguration()->GetDatabase()->CreateChannelRightDefault(user->GetId(), channel->GetId());
		result = Configuration::GetConfiguration()->GetDatabase()->SelectChannelRight(user->GetId(), channel->GetId());
	}
	std::vector<bool> vectorRight;
	vectorRight.push_back((*result->at(0))["canCreate"]->GetValueBool());
	vectorRight.push_back((*result->at(0))["canDelete"]->GetValueBool());
	vectorRight.push_back((*result->at(0))["canEdit"]->GetValueBool());
	vectorRight.push_back((*result->at(0))["canEditUser"]->GetValueBool());
	vectorRight.push_back((*result->at(0))["canTalk"]->GetValueBool());
	vectorRight.push_back((*result->at(0))["canWrite"]->GetValueBool());
	vectorRight.push_back((*result->at(0))["canKick"]->GetValueBool());
	vectorRight.push_back((*result->at(0))["canBan"]->GetValueBool());
	ChannelRight* right = new ChannelRight((*result->at(0))["id"]->GetValueInt(), vectorRight);
	delete result;
	this->_userChannelRight[user][channel] = right;
	return *right;
}


void		RightManager::SetChannelRight(IUser* user, IChannel* channel, const bool canCreate, const bool canDelete, const bool canEdit, const bool canEditUser, const bool canTalk, const bool canWrite, const bool canKick, const bool canBan)
{
	// modif map si donnee existante dans map, et la db en meme tps
	if(this->_userChannelRight.count(user) && this->_userChannelRight[user].count(channel))
		this->_userChannelRight[user][channel]->SetChannelRight(canCreate, canDelete, canEdit, canEditUser, canTalk, canWrite, canKick, canBan);
	else
	{
		// sinon on modif seulement dans la base
		unsigned int id = Configuration::GetConfiguration()->GetDatabase()->SelectChannelRightId(user->GetId(), channel->GetId());
		//ici on peut check si une erreur a ete emise, si c'est le cas on cree un right par default
		Configuration::GetConfiguration()->GetDatabase()->UpdateChannelRight(id, canCreate, canDelete, canEdit, canEditUser, canTalk, canWrite, canKick, canBan);
	}
}